package com.lgCore.clientHandler;


import com.lgCore.clientCocurrent.RpcTaskCallable;
import com.lgCore.nettyCocurrent.ExecutorScheduler;
import com.lgCore.protoModel.ProtoMsg;
import com.lgCore.queue.ClientResultQueue;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RpcMsgHandler extends ChannelInboundHandlerAdapter {
    Logger log = LoggerFactory.getLogger(RpcMsgHandler.class);
    /**
     * 业务逻辑处理
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //判断消息实例
        if (null == msg || !(msg instanceof ProtoMsg.Message)) {
            super.channelRead(ctx, msg);
            return;
        }

        //判断类型
        ProtoMsg.Message message = (ProtoMsg.Message) msg;
        ProtoMsg.HeadType headType = message.getRpcResponse().getType();
        if (!headType.equals(ProtoMsg.HeadType.RPC_RESPONSE)) {
            super.channelRead(ctx, msg);
            return;
        }
        //判断类型
        //异步处理转发的逻辑
        RpcTaskCallable rpcTaskCallable = new RpcTaskCallable(message);
//        FutureTaskScheduler.add(rpcTaskCallable);
        ExecutorScheduler.add(rpcTaskCallable);



//        List<ByteString> byteStringList = message.getMsgDataList();
//        System.out.println(" 收到消息 from -> " + message.getRpcResponse());
  }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // ..

        //捕捉异常信息
        cause.printStackTrace();
        ctx.close();


    }
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //这里执行客户端断开连接后的操作
        String ipAddr = ctx.channel().remoteAddress().toString();
        ipAddr = ipAddr.substring(1, ipAddr.length());
        //删除netty连接
        log.info("客户端：与服务端断开连接" + ipAddr);

    }
}
